﻿#include "loopque.h"
#include <QDebug>
loopQue::loopQue(QObject *parent) :
    QObject(parent)
{
    loopque.resize(10);
    loopque.fill(0);
    headnum = 0;
    rearnum = loopque.size()-1;

    lastNum = -1;
    backNum = 0;
}

void loopQue::push(int value)
{
    if(lastNum == value){
        return;
    }
    lastNum = value;

    if(headnum+1 > loopque.size()-1){
        if (rearnum == 0){
            rear++;
        }
    }else{
        if (headnum+1 == rearnum){
            if(rearnum == loopque.size()-1){
                rearnum = 1;
            }else{
                rearnum++;
            }
        }
    }

    loopque.replace(headnum,value);

    if(headnum == loopque.size()-1){
        headnum = 0;
    }else{
        headnum++;
    }
    //qDebug()<<loopque<<headnum<<rearnum;
}

int loopQue::back()
{
    if ((headnum == rearnum+1)||(headnum == 0&&rearnum == loopque.size()-1)){
        return loopque.at(headnum);
    }
    if(headnum == 0){
        headnum = loopque.size()-1;
    }else{
        headnum--;
    }
    backNum++;
    qDebug()<<loopque<<headnum<<rearnum;
    return loopque.at(headnum);
}

int loopQue::next()
{
    int ret;
    if (backNum<=0){
        return loopque.at(headnum-1);
    }
    ret = loopque.at(headnum);

    if(headnum == loopque.size()-1){
        headnum = 0;
    }else{
        headnum++;
    }
    backNum--;
    qDebug()<<loopque<<headnum<<rearnum;
    return ret;
}
